<?php
declare(strict_types=1);
namespace Aincrid\MySwoole;

use Swoole\Coroutine\Context;
use Swoole\Http\Request as SwooleRequest;
use Co;

class Request
{
    protected ?SwooleRequest $request = null;

    public int $cid = 0;

    public array $params = [];
    /**
     * 协程上下文
     */
    public ?Context $context = null;

    public function __construct(SwooleRequest $request)
    {
        $this->request = $request;
        $this->setCid();
        $this->setContext();
    }

    protected function setCid()
    {
        $this->cid = Co::getCid();
    }

    public function getCid(): int
    {
        return $this->cid;
    }

    protected function setContext()
    {
        $this->context = Co::getContext($this->cid);
    }

    public function getContext(): ?Context
    {
        return $this->context;
    }

    public function contextSet(string $key, $value)
    {
        $this->context[$key] = $value;
    }

    public function contextGet(string $key)
    {
        return $this->context[$key];
    }

    public function header(string $key): array|string
    {
        if (empty($key)) {
            return $this->request->header;
        }
        return $this->request->header[$key] ?? '';
    }

    public function server(string $key): array|string
    {
        if (empty($key)) {
            return $this->request->server;
        }
        return $this->request->server[$key] ?? '';
    }

    public function get(string $key): string
    {
        return $this->request->get[$key] ?? '';
    }

    public function post(string $key): string
    {
        return $this->request->post[$key] ?? '';
    }

    public function param(string $key): string|int
    {
        return $this->params[$key] ?? '';
    }

    public function raw(): string
    {
        return $this->request->getContent();
    }

    public function files(): array
    {
        return $this->request->files;
    }

    public function url(): string
    {
        return $this->server('path_info');
    }

    public function method(): bool|string
    {
        return $this->request->getMethod();
    }

}